<?php
namespace app\common\logic;

use RobThree\Auth\TwoFactorAuth;
use think\facade\Env;

class TwoFactor  extends Base {

    /**
     * @desc 创建二步验证密钥
     * @param string $userName
     * @param string $moduleName
     * @return false|string|array
     * @throws \Exception
     */
    public function createTwoFactor($userName, $moduleName = 'user') {
        $site_name = model('SiteConfig')->getConfigValue('site_name');
        $tfa = new TwoFactorAuth($site_name.'-'.$moduleName);
        $secret = $tfa->createSecret();
        $imgUri = $tfa->getQRCodeImageAsDataUri($site_name.'-'.$moduleName.':'.$userName, $secret);
        return [
            'secret' => $secret,
            'image'  => $imgUri
        ];
    }

    /**
     * @desc 验证二步验证的6位数字验证码
     * @param string $secret
     * @param string $code 6位安全验证码
     * @param string $moduleName 模块名称
     * @return bool
     * @throws \Exception
     */
    public function verifyTwoFactorCode($secret, $code, $moduleName = 'user') {
        $site_name = model('SiteConfig')->getConfigValue('site_name');
        $tfa = new TwoFactorAuth($site_name.'-'.$moduleName);
        return $tfa->verifyCode($secret, $code);
    }
}